/**
 * 定义一个栈
 */
function Stack() {
    this.data = [];
    this.top = -1;
    this.size = 0;
}
Stack.prototype.push = function (...item) {
    let len = item.length;
    for (let i = 0; i < len; i++) {
        this.data[++this.top] = item[i];
        this.size++;
    }
}
Stack.prototype.pop = function () {
    if (this.top < 0) {
        throw new Error("Out Of Bound");
    }
    this.size--;
    return this.data[this.top--];
}
Stack.prototype.peek = function () {
    if (this.top < 0) {
        throw new Error("Out Of Bound");
    }
    return this.data[this.top];
}
Stack.prototype.getSize = function () {
    return this.size;
}

/**
 * 定义一个队列
 */
function Queue() {
    this.data = [];
    this.top = -1;
    this.size = 0;
}

Queue.prototype.push = function (...item) {
    let len = item.length;
    for (let i = 0; i < len; i++) {
        this.data[++this.top] = item[i];
        this.size++;
    }
}

Queue.prototype.pop = function () {
    if (this.top < 0) {
        throw new Error("Out Of Bound");
    }
    let ans = this.data[0];
    this.data.splice(0, 1);
    this.top--;
    this.size--;
    return ans;
}
Queue.prototype.getSize = function () {
    return this.size;
}
Queue.prototype.getData = function () {
    return this.data;
}


/**
 * 用栈来模拟队列
 */
function MyQueue() {
    this.stackIn = new Stack();
    this.stackOut = new Stack();
}
MyQueue.prototype.push = function (...item) {
    this.stackIn.push(...item);
}

MyQueue.prototype.pop = function () {
    if (this.stackOut.getSize() > 0){
        return this.stackOut.pop();
    }else{
        if(this.stackIn.getSize() <= 0){
            throw new Error("No item any more")
        }
        let len = this.stackIn.getSize();
        while(len--){
            this.stackOut.push(this.stackIn.pop());
        }
        return this.stackOut.pop();
    }
}

// let q = new MyQueue();
// q.push(2,4,5,6);
// console.log(q.pop())
// q.push(3,8,0,9)
// console.log(q.pop())
// console.log(q.pop())
//成功

/**
 * 用队列来实现栈
 * 在将一个元素 x 插入队列时，为了维护原来的后进先出顺序，
 * 需要让 x 插入队列首部。而队列的默认插入顺序是队列尾部，因此在将 x 插入队列尾部之后，需要让除了 x 之外的所有元素出队列，再入队列。
 */
function MyStack(){
    this.queue = new Queue();
}
//在push之后，要先将之前的元素全都pop出来，再次push进去，这样才能保证每次出队的元素是最后进入的元素
MyStack.prototype.push = function(...item){
    this.queue.push(...item);
    let len = this.queue.getSize();
    len--;
    while(len--){
        this.queue.push(this.queue.pop())
    }
}
MyStack.prototype.pop = function(){
    return this.queue.pop();
}
MyStack.prototype.getData = function(){
    return this.queue.getData();
}
let s = new Stack();
s.push(1,4,5,6);
console.log(s.pop());
console.log(s.pop());
console.log(s.pop());